package cn.elricyu.tt.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.elricyu.tt.bean.User;
import cn.elricyu.tt.contant.Constant;
import cn.elricyu.tt.db.bean.Account;
import cn.elricyu.tt.db.bean.LoginAccount;
import cn.elricyu.tt.db.dao.AccountDAO;
import cn.elricyu.tt.db.dao.LoginAccountDAO;

public class UserService {
    public static void saveOrUpdateUser(User user) {
        Account account = user.getAccount();
        Account dbAccount = AccountDAO.get(account.getId());
        if (dbAccount == null) {
            AccountDAO.add(account);
        } else {
            if (StringUtils.isBlank(account.getSn()) && StringUtils.isNotBlank(dbAccount.getSn())) {
                account.setSn(dbAccount.getSn());
                user.setSn(dbAccount.getSn());
            }
            AccountDAO.update(account);
        }
    }

    public static List<User> getUserList() {
        List<User> userList = new ArrayList<User>();
        List<Account> accountList = AccountDAO.getAll();
        if (!accountList.isEmpty()) {
            for (Account account : accountList) {
                if (userList.size() >= Constant.SYSTEM_MAX_USER) {
                    break;
                }
                userList.add(new User(account));
            }
        }
        return userList;
    }

    public static void saveOrUpdateLoginAccount(LoginAccount account) {
        LoginAccount dbAccount = LoginAccountDAO.get(account.getOpenid());
        if (dbAccount == null) {
            LoginAccountDAO.add(account);
        } else {
            LoginAccountDAO.update(account);
        }
    }

    public static List<LoginAccount> getLoginAccountList() {
        return LoginAccountDAO.getAll();
    }

    public static void deleteUser(User user) {
        AccountDAO.delete(user.getId());
    }
}
